<template>
  <div>
    <a-input-search
        placeholder="请输入地址"
        v-model="searchAddress"
        @search="handleSearch"
    >
      <a-button slot="enterButton" type="primary">搜索</a-button>
    </a-input-search>
    <!-- 地图容器，用于承载高德地图 -->
    <div id="container" style="height: 500px;"></div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  data() {
    return {
      visible: false,
      areaList: [],
      areaValue: '',
      map: null,
      loading: false,
      checkedForm: {},
      marker: null,
      AutoComplete: null,
      aMap: null,
      geoCoder: null,
      searchAddress: '',
      currentPosition: null,
      receiptAddress: '',
      detailsAddress: '',
    };
  },
  created() {
    // 如果需要在组件创建时执行逻辑，可以使用 created 钩子
  },
  mounted() {
    this.initMap();
    this.getCurrentPosition();
  },
  unmounted() {
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    initMap() {
      this.aMap = null;
      this.geoCoder = null;
      this.map = null;
      this.marker = null;
      this.AutoComplete = null;

      window._AMapSecurityConfig = {
        securityJsCode: "22eb2a5d976ac6fc90e501c3264d30dd",
      };

      AMapLoader.load({
        key: "23405e95488ea44adb93a5fe065f7886",
        version: "2.0",
        plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
      }).then((AMap) => {
        this.aMap = AMap;
        this.map = new this.aMap.Map("container", {
          viewMode: "3D",
          zoom: 11,
          center: [116.397428, 39.90923],
        });
        this.AutoComplete = new this.aMap.AutoComplete({
          city: '全国',
        });
        this.geoCoder = new this.aMap.Geocoder({
          city: "010",
          radius: 1000,
        });
        this.map.on('click', this.mapClickHandler);
      }).catch((e) => {
        console.error(e);
      });
    },
    //获取当前位置
    getCurrentPosition() {
      if ('geolocation' in navigator) {
        navigator.geolocation.getCurrentPosition(
            (position) => {
              const { longitude, latitude } = position.coords;
              this.currentPosition = [longitude, latitude]; //
              this.updateMap(longitude,latitude)
              this.map.setCenter(new AMap.LngLat(...this.currentPosition)); // 将地图中心点设置为当前位置
              // console.log("longitude,latitude",longitude,latitude)
              this.getAddressByCoords(longitude,latitude);
            },
            () => {
              console.error('无法获取定位');
            },
            {
              enableHighAccuracy: true,
              timeout: 10000,
              maximumAge: 0,
            }
        );
      } else {
        console.error('浏览器不支持Geolocation');
      }
    },
    mapClickHandler(event) {
      if (this.marker) {
        this.map.remove(this.marker);
      }
      this.marker = new this.aMap.Marker({
        position: new this.aMap.LngLat(event.lnglat.getLng(), event.lnglat.getLat()),
        title: '点击位置',
      });
      this.checkedForm = {
        lat: event.lnglat.getLat(),
        lng: event.lnglat.getLng(),
      };
      this.map.add(this.marker);
      this.map.setCenter(new this.aMap.LngLat(event.lnglat.getLng(), event.lnglat.getLat()));
      this.getAddressByCoords(event.lnglat.getLng(), event.lnglat.getLat())
    },
    //触发搜索
    handleSearch() {
      if (this.searchAddress) {
        this.searchAddressGeocoding();
      }
    },
    //根据输入位置进行搜索
    searchAddressGeocoding() {
      console.log("执行搜索")
      const autoComplete = new AMap.AutoComplete({
        city: "全国", // 城市设为全国
      });
      autoComplete.search(this.searchAddress, (status, result) => {
        // console.log(status,result)
        if (status === 'complete' && result.info === 'OK') {
          const geocode = new AMap.Geocoder({
            city: "全国",
          });
          const firstResult = result.tips[0];
          geocode.getAddress(firstResult.location, (geocodeStatus, geocodeResult) => {
            if (geocodeStatus === 'complete' && geocodeResult.info === 'OK') {
              this.updateMap(firstResult.location.lat, firstResult.location.lng);
              // console.log(firstResult.location.lat, firstResult.location.lng)
              this.getAddressByCoords(firstResult.location.lng,firstResult.location.lat)
            }
          });
        }
      });
    },
    //更新地图位置
    updateMap(lat, lng) {
      // 检查地图实例是否存在
      if (this.map) {
        console.log("地图实例存在")
        if (this.marker) {
          console.log("移除标记")
          // 如果已有标记，先移除
          this.map.remove(this.marker);
        }
        // 使用 AMap.Marker 而不是 this.map.Marker 来创建新的标记
        this.marker = new AMap.Marker({
          position: new AMap.LngLat(lng, lat), // 高德地图的经纬度对象
          title: '用户位置', // 鼠标悬停时显示的标题
        });
        // 将新标记添加到地图上
        this.map.add(this.marker);
        // 设置地图的中心点和缩放级别
        this.map.setCenter(new AMap.LngLat(lng, lat));
        console.log(`设置地图中心到：${lat}, ${lng}`);
        this.map.setZoom(14); // 根据需要设置合适的缩放级别
        this.getAddressByCoords();
      }
    },
    getAddressByCoords(longitude, latitude) {
      if (isNaN(longitude) || isNaN(latitude)) {
        console.error('无效的经纬度参数');
        return;
      }
      const geocode = new AMap.Geocoder({
        radius: 1000,
      });
      geocode.getAddress([longitude,latitude], (status, result) => {
        console.log(longitude,latitude)
        console.log(status,result)
        if (status === 'complete' && result.info === 'OK' && result.regeocode) {
          this.receiptAddress=[result.regeocode.addressComponent.province, result.regeocode.addressComponent.city, result.regeocode.addressComponent.district]
          this.detailsAddress=result.regeocode.addressComponent.township+result.regeocode.addressComponent.street;
          console.log(this.receiptAddress,this.detailsAddress)
          this.convenyValue();
        } else {
          console.log('根据经纬度查询地址失败', status, result.info);
        }
      });
    },
    convenyValue(){
      this.$emit('update:addresses', {
        receiptAddress: this.receiptAddress,
        detailsAddress: this.detailsAddress
      });
      // console.log("执行传值")
    },
    open() {
      this.initMap();
      this.visible = true;
    },
  },
};
</script>

